// pages/consume/consume.js
const API = require('../../utils/api.js');
const TOAST = require('../../utils/toast.js');
const AJAX = require('../../utils/ajax.js');
// 引入腾讯地图
const qqMapWxUtil = require('../../utils/qqMapWxUtil.js')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 金额
    money: 0,
    isShow: false,
    //保存消费类型数据
    consumeTypeList: [],
    //服务器图片地址
    imageHost: API.api.imageHost,
    //点击的保存id
    consumeTypeId: 1,
    //要显示的图标信息
    consumeType: {},
    //地理位置
    address: '',
    // 详情地址
    addressDetail: '',
    // 省 市 区
    region: [],
    // 上传保存的图片
    imagePathList: [],
    //导航栏显示颜色
    showType: true,
    // 计算器集合
    calculatorList:[
      [{ "value": "7" }, { "value": "8" }, { "value": "9" }],
      [{ "value": "4" }, { "value": "5" }, { "value": "6" }],
      [{ "value": "1" }, { "value": "2" }, { "value": "3" }],
      [{ "value": "C" }, { "value": "0" }, { "value": "." }]],
    current: '0',
    loading: false,
    isShowImage: false, // 显示图片弹框
    isUploadFile: false, // 判断页面是跳转还是上传图片
    swiperHeight: 450, // 初始化的swiper高度
    imgheights: [], //所有图片的高度 
    current: 0,//默认  
    isShowContent: false, // 显示内容弹框
    remarks: '', // 备注
    tmplIds: [API.api.bookkeepingSuccess,API.api.accountingBudget], // 模板id
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(`这里是onLoad`, options)
    console.log(`这里是onLoad,地址来哪里` + options.form)
    console.log(`这里是onLoad,地址来哪里` + options.address)
    console.log(`这里是onLoad,详情地址来哪里` + options.addressDetail)
    if (options.form === 'address') {
      this.setData({
        address: options.address,
        addressDetail: options.addressDetail
      })
    } else {
      // 获取到微信地理位置
      this.getWxLocation()
    }
    // 获取消费类型数据,默认值为0
    this.getConsumeType(0);
  },
  /**
   * 获取当前位置信息
   */
  getWxLocation() {
    console.log(`我要去获取位置信息`)
    let that = this
    wx.getLocation({
      type: 'gcj02',
      success: function(res) {
        // 调用腾讯地图显示位置信息
        that.reverseGeocoder(res.latitude, res.longitude)
      },
    })
  },
  /**
   *调用腾讯地图显示位置信息
   * latitude:纬度
   * longitude：经度
   */
  reverseGeocoder(latitude, longitude) {
    console.log(`reverseGeocoder------latitude:` + latitude + `longitude:` + longitude)
    let that = this
    let location = {}
    location.latitude = latitude;
    location.longitude = longitude;
    qqMapWxUtil.reverseGeocoder(location).then(response => {
      //当前位置信息
      that.setData({
        address: response.address,
        region: response.region,
        addressDetail: response.addressDetail
      })
    })
  },
  /**
   * 上传图片
   */
  uploadFile(event) {
    if (this.data.imagePathList.length > 0 && event.currentTarget.dataset.upload == undefined) {
      this.setData({
        isShowImage: true
      })
      return;
    }
    let that = this
    wx.chooseImage({
      count: 2,
      sizeType: ['compressed'],
      success: function(res) {
        const tempFiles = res.tempFiles;
        let requestUrl = API.api.uploadFile + '/bookkeeping/bookkeeping'
        var imagePathListObj = that.data.imagePathList
        for (var i = 0; i < tempFiles.length; i++) {
          if (tempFiles[i].size > 1048576) {
            TOAST.showToastSuccess('图片大于1M')
            continue;
          }
          that.setData({
            loading: true
          })
          wx.uploadFile({
            url: requestUrl,
            filePath: tempFiles[i].path,
            name: 'file',
            header: {
              "Authorization": wx.getStorageSync('token')
            },
            success: function(res) {
              let resData = JSON.parse(res.data)
              if (resData.code == 200) {
                switch (imagePathListObj.length) {
                  case 0:
                    imagePathListObj.push(resData.data)
                    break;
                  default:
                    imagePathListObj[1] = imagePathListObj[0]
                    imagePathListObj[0] = resData.data
                    break;
                }
                that.setData({
                  imagePathList: imagePathListObj
                })
                TOAST.showToastSuccess('上传成功')
              }
            },
            complete() {
              that.setData({
                loading: false
              })
            }
          })
        }
      }
    })
  },
  /**
   * 上传指定图片
   * @param {*} event 
   */
  uploadOneFile(event) {
    let that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      success: function(res) {
        const tempFiles = res.tempFiles[0];
        let requestUrl = API.api.uploadFile + '/bookkeeping/bookkeeping'
        var imagePathListObj = that.data.imagePathList
        console.log(tempFiles)
        if (tempFiles.size > 1048576) {
          TOAST.showToastSuccess('图片大于1M')
        }
        that.setData({
          loading: true
        })
        wx.uploadFile({
          url: requestUrl,
          filePath: tempFiles.path,
          name: 'file',
          header: {
            "Authorization": wx.getStorageSync('token')
          },
          success: function(res) {
            let resData = JSON.parse(res.data)
            if (resData.code == 200) {
              imagePathListObj[event.currentTarget.dataset.index] = resData.data
              that.setData({
                imagePathList: imagePathListObj
              })
              TOAST.showToastSuccess('上传成功')
            }
          },
          complete() {
            that.setData({
              loading: false
            })
          }
        })
      }
    })
  },
  /**
   * 跳转定位
   */
  gotoAddress() {
    wx.navigateTo({
      url: '../index/address/address?form=consume&address=' + this.data.address + '&addressDetail=' + this.data.addressDetail,
    })
  },
  /**
   * 支出收入类型转换
   */
  tabTap: function(event) {
    let showType = event.currentTarget.dataset.type == 1 ? false : true
    this.setData({
      showType: showType
    })
    this.getConsumeType(event.currentTarget.dataset.type)
  },
  handleChange({
    detail
  }) {
    this.setData({
      current: detail.key
    });
    this.getConsumeType(detail.key)
  },
  getConsumeType: function(type) {
    let that = this;
    let requestUrl = API.api.consumeTypes + '/type?type=' + type;
    AJAX.getRequest(requestUrl).then(response => {
      that.setData({
        consumeTypeList: response.data,
        consumeType: response.data[0]
      })
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },
  submitInfo: function(e) {
    if (e.detail.formId) {
      AJAX.saveFormId(e.detail.formId)
    }
  },
  btnIcon: function(event) {
    let that = this
    console.log('你是不是点击了icon' + JSON.stringify(event.currentTarget.dataset.type))
    this.data.consumeTypeList.forEach(item => {
      if (item.id == event.currentTarget.dataset.type) {
        // 进行保存数据信息
        console.log('匹配到了。。。。。。' + item.id)
        that.setData({
          consumeType: item,
          consumeTypeId: event.currentTarget.dataset.type
        })
        return;
      }
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  /**
   * 添加数据
   */
  calculationType(event) {
    switch (event.currentTarget.dataset.type) {
      case '0':
      case '1':
      case '2':
      case '3':
      case '4':
      case '5':
      case '6':
      case '7':
      case '8':
      case '9':
        //常规数字
        this.addMunber(event)
        break;
      case '.':
        // 添加小数点
        this.addSpot()
        break;
      case 'DEL':
        // 删除
        this.deleteNumber(event)
        break;
        // 归零
      case 'C':
        this.reset();
        break;
      default:
        console.log(`键盘` + event.currentTarget.dataset.type + `匹配不到对于的类型`)
    }
  },
  addMunber: function(event) {
    // 先判断是否有小数点
    let message = String(this.data.money);
    let index = message.lastIndexOf('.');
    if (index != -1) {
      if (message.length - index > 2) {
        return
      }
    }
    if (message != 0 || index != -1) {
      message += event.currentTarget.dataset.type
    } else {
      message = event.currentTarget.dataset.type
    }
    this.setData({
      money: message
    })
  },
  deleteNumber: function() {
    let message = this.data.money;
    if (message != 0 && message != '') {
      message = message.substring(0, message.length - 1)
    } else {
      message = '0'
    }
    this.setData({
      money: message
    })
  },
  addSpot: function() {
    let money = this.data.money + "";
    console.log(money)
    let index = money.lastIndexOf('.');
    if (index != -1) {
      return
    }
    this.setData({
      money: money + '.'
    })
  },
  reset: function() {
    this.setData({
      money: 0,
      isShow: false,
    })
  },
  /**
   * 保存按钮
   */
   saveBookkeeping() {
    let that = this
    // 进行loaing
    if (this.data.loading) {
      return;
    }
    this.setData({
      loading: true
    })
    let money = Number(this.data.money);
    if (money == 0) {
      TOAST.showToastSuccess('金额不能为0')
      this.setData({
        loading: false
      })
      return
    }
    
    // 进行金额转换
    money = money * 100;
    let requestObj = {};
    requestObj.userId = wx.getStorageSync('userId');
    requestObj.consumeTypeId = this.data.consumeTypeId;
    requestObj.money = money;
    requestObj.address = this.data.address;
    requestObj.addressDetail = this.data.addressDetail;
    requestObj.imageUrl = JSON.stringify(this.data.imagePathList);
    requestObj.remarks = this.data.remarks
    console.log('保存的数据来着', requestObj)
    let requestUrl = API.api.bookkeepings;
    AJAX.postRequest(requestUrl, requestObj).then(response => {
      that.setData({
        loading: false
      })
      wx.switchTab({
        url: '/pages/index/index'
      })
    })
  },
  hideModel() {
    this.setData({
      isShowImage: false,
      isShowContent:false
    })
  },
  onTabItemTap(item) {
    this.setData({
      money: 0,
      addorDel: '+',
      isShow: false,
      imagePathList: [],
      current: 0,
      isShowImage: false,
      isShowContent:false,
      loading:false
    })
    // 获取消费类型数据,默认值为0
    this.getConsumeType(0);
  },
  // 设置高度
  imageLoad: function(e) { //获取图片真实宽度  
    var imgwidth = e.detail.width;
    var imgheight = e.detail.height;
    //宽高比  
    var ratio = imgwidth / imgheight;
    console.log(imgwidth, imgheight)
    //计算的高度值  
    var viewHeight = 750 / ratio;
    imgheight = viewHeight;
    var imgheights = this.data.imgheights;
    //把每一张图片的对应的高度记录到数组里
    imgheights[e.target.dataset.index] = imgheight;
    this.setData({
      imgheights: imgheights
    })
  },
  bindchange: function(e) {
    this.setData({
      current: e.detail.current
    })
  },
  showContent() {
    this.setData({isShowContent: true})
  },
  /**
   * 填写备注
   */
  textareaRemark:function(e) {
    console.log(`获取到数据了`,e.detail.value)
    this.setData({ remarks:e.detail.value })
  },
  /**
   *  获取一次性订阅信息
   */
  requestSubscribeMessage() {
    let that = this;
    // 用户想接收到模板消息
    if(wx.getStorageSync('sendMessage') == 0) {
      that.saveBookkeeping();
      return;
    }
    console.log(that.data.tmplIds)
    wx.requestSubscribeMessage({
      tmplIds: that.data.tmplIds,
      success(success) {
        // 保存用户提交信息
        that.saveWxUserSubscribe(success);
      },
      fail(error) {
        console.error(`调用接口失败`);
      },
      complete() {
        that.saveBookkeeping()
      }
    })
  },
  saveWxUserSubscribe(resData) {
    let that = this
    this.data.tmplIds.forEach(item => {
      console.log(`resData[item]` + resData[item])
      let requestObj = {};
      requestObj.userId = wx.getStorageSync('userId');
      if(resData[item] == 'accept') {
        requestObj.type = 1;
      } else if (resData[item] == 'reject') {
        requestObj.type = 0;
      } else {
        requestObj.type = 2;
      }
      requestObj.subscribeId = item;
      console.log('保存的数据来着', requestObj)
      let requestUrl = API.api.wxusersubscribes;
      AJAX.postRequest(requestUrl, requestObj).then(response => {
          console.log(`保存成功`)
      })
    })
  }
})